package com.datatest.config;

import com.sun.istack.internal.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author lxt
 * Created by Jccfc on 2021/11/1.
 */
@Slf4j
@Component
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {
    @Override
    @NotNull
    public synchronized RestTemplateResponseInterceptor intercept(HttpRequest httpRequest, @NotNull byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        log.info("------------------------request----------------------------");
        log.info("request url:"+httpRequest.getURI());
        log.info("request method:"+httpRequest.getMethod());
        log.info("request headers:"+httpRequest.getHeaders().toString());
        log.info("request body:"+new String(bytes, StandardCharsets.UTF_8));
        ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);
        try {
            //响应成功就打印响应日志
            if(response.getStatusCode() == HttpStatus.OK){
                byte[] outByte = new byte[1024];
                int len = 0;
                //读取响应的字节流
                while ((len=response.getBody().read(outByte))>0) {
                    outputStream.write(outByte, 0, len);
                }
            }
        } finally {
            outputStream.close();
            response.close();
        }
        log.info("------------------------response----------------------------");
        log.info("response code:"+response.getStatusCode());
        log.info("response text:"+response.getStatusText());
        log.info("response headers:"+response.getHeaders().toString());
        //获取响应字节流最大的字节数，转成字节，字符
        log.info("response body:"+ new String(outputStream.toByteArray(),StandardCharsets.UTF_8));
        return new RestTemplateResponseInterceptor(response,new ByteArrayInputStream(outputStream.toByteArray()));
    }
}
